<?php
declare(strict_types=1);
namespace App\Helper;

use Elasticsearch\Client;
use Elasticsearch\ClientBuilder;

/**
 * es一些共用的工具方法
 * Trait EsTrait
 * @package App\Elasticsearch
 */
trait EsTrait
{
    /**
     * 获取请求client
     * @return Client
     */
    public static function getClient(): Client
    {
        $builder = ClientBuilder::create();
        $host = env('ELASTICSEARCH_HOST', 'http://127.0.0.1:9200');
        return $builder->setHosts([$host])->build();
    }

    /**
     * 判断索引是否存在
     * @param Client $client
     * @param $index
     * @return bool
     */
    public static function indexExists(Client $client, $index): bool
    {
        return $client->indices()->exists(['index' => $index]);
    }

    /**
     * 判断别名是否存在
     * @param Client $client
     * @param $alias
     * @return bool
     */
    private static function aliasExists(Client $client, $alias): bool
    {
        return $client->indices()->existsAlias(['name' => $alias]);
    }

    /**
     * 根据文档id判断文档是否存在
     * @param Client $client
     * @param $index
     * @param $id
     * @return bool
     */
    private static function isDocumentExists(Client $client, $index, $id): bool
    {
        return $client->exists([
            'index' => $index,
            'type' => self::HOSPITAL_TYPE,
            'id' => $id
        ]);
    }
}
